package com.whmnx.chitchat.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Process;
import android.util.Log;


import androidx.multidex.MultiDex;

import com.microsoft.signalr.HubConnection;
import com.microsoft.signalr.HubConnectionBuilder;
import com.microsoft.signalr.HubConnectionState;
import com.microsoft.signalr.OnClosedCallback;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.imsdk.TIMSdkConfig;
import com.tencent.imsdk.session.SessionWrapper;
import com.tencent.qcloud.tim.uikit.TUIKit;
import com.tencent.qcloud.tim.uikit.config.GeneralConfig;
import com.tencent.qcloud.tim.uikit.config.TUIKitConfigs;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.whmnx.chitchat.utils.LogUtil;
import com.whmnx.chitchat.utils.SPUtil;
import com.whmnx.chitchat.utils.UItils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Administrator
 */
public class BaseApplication extends Application {

    public static Map<String, Long> map;
    private static Context context;
    private static BaseApplication mInstance;
    /**
     * 主线程ID
     */
    private static int mMainThreadId = -1;
    /**
     * 主线程ID
     */
    private static Thread mMainThread;

    /**
     * 主线程Handler
     */
    private static Handler mMainThreadHandler;

    private HubConnection hubConnection;
    private boolean isConnect;//是否连接成功

    private static List<Activity> records = new ArrayList<>();

    public static synchronized Context getContext() {
        if (context == null) {
            return  getApplication();
        }
        return context;
    }

    public static BaseApplication getApplication() {
        return mInstance;
    }

    /**
     * 获取主线程ID
     */
    public static int getMainThreadId() {
        return mMainThreadId;
    }

    /**
     * 获取主线程
     */
    public static Thread getMainThread() {
        return mMainThread;
    }

    /**
     * 获取主线程的handler
     */
    public static synchronized Handler getMainThreadHandler()
    {
        if (mMainThreadHandler == null) {
            return new Handler();
        }
        return mMainThreadHandler;
    }

    public static void perfectExit() {
        for (Activity activity : records) {
            activity.finish();
        }
    }

    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator((context, layout) -> {
            //全局设置主题颜色
            return new ClassicsHeader(context);
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator((Context context, RefreshLayout layout) -> {
            //指定为经典Footer，默认是 BallPulseFooter
            return new ClassicsFooter(context);
        });
    }


    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        mMainThreadId = Process.myTid();
        mMainThread = Thread.currentThread();
        mMainThreadHandler = new Handler();
        mInstance = this;
       // MobSDK.init(this);

        LogUtil.init();

    //   Bugly.init(getApplicationContext(), "e5a49a70e3", false);

        //判断是否是在主线程
      if (SessionWrapper.isMainProcess(getApplicationContext())) {
            // 配置 Config，请按需配置
            TUIKitConfigs configs = TUIKit.getConfigs();
            //1400275963
     //       configs.setSdkConfig(new TIMSdkConfig(1400401917));
            configs.setGeneralConfig(new GeneralConfig());
            TUIKit.init(this, 1400401917, configs);
        }

     //   if (hubConnection == null)//创建连接
          //  hubConnection = HubConnectionBuilder.create("http://192.168.0.18:8019/hubs/codebuild").build();

         /*   hubConnection.onClosed(new OnClosedCallback() {//断开连接监听（这里一般不会走）
            @Override
            public void invoke(Exception exception) {
                UItils.showToastSafe("已断开连接");
                //   disConnect(false);
            }
        });*/
     //   hubConnect();

        UMConfigure.init(this, "5f86b78394846f78a9726a73", "Umeng", UMConfigure.DEVICE_TYPE_PHONE, "4c301ee94c00ae1ce522e4ba9e9c648d");

        //获取消息推送代理示例
        PushAgent mPushAgent = PushAgent.getInstance(this);
//        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER); //服务端控制声音


        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回deviceToken deviceToken是推送消息的唯一标志
                Log.i("hhh","注册成功：deviceToken：-------->  " + deviceToken);
                SPUtil.put("deviceToken",deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
                Log.e("hhh","注册失败：-------->  " + "s:" + s + ",s1:" + s1);
            }
        });
    }



    private void hubConnect() {
        hubConnection.start().blockingAwait();//开始进行连接
        try {
            isConnect = isConnected();//判断是否已经连接
           // connect.setText(isConnect ? "断开" : "连接");
         //   UItils.showToastSafe(isConnect ? "连接成功" : "连接失败");
        } catch (Exception e) {
            isConnect = false;
            UItils.showToastSafe("服务器发生异常");
        }
    }


    /**
     * 检测是否连接
     */
    private boolean isConnected() {
        if (hubConnection != null && hubConnection.getConnectionState() == HubConnectionState.CONNECTED)//这样判断并不准确
            return true;
            return false;
    }

    private void startCallService() {
        Log.e("hhh", "startCallService-------------");
       // Intent intent = new Intent(this, CallService.class);
      //  startService(intent);
    }

    public synchronized static BaseApplication getInstance() {
        if (mInstance == null) {
            return new BaseApplication();
        }
        return mInstance;
    }



    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // you must install multiDex whatever tinker is installed!
        MultiDex.install(base);
    }

    public void addActvity(Activity activity) {
        records.add(activity);
    }

    public void removeActvity(Activity activity) {
        records.remove(activity);
    }

    //遍历所有Activity并finish
    public void exit(){
        if (null != records && records.size() > 0) {
            for (Activity activity : records) {
                //依次关闭
                activity.finish();
            }
        }
        //强制退出
        System.exit(0);
    }
}
